/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stcu.forms;

/**
 *
 * @author roi
 */
public class ChatForm extends javax.swing.JFrame {
    

    /**
     * Creates new form ChatForm
     */
    public ChatForm() {
        initComponents();
    }


        messageLogText.setEditable(false);
        memberList.setModel(userListModel);
        group.addListener(this);

        handleButtons();
        group.listMembers();
		
		jScrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		messageLogText.setLineWrap(true);
		
		DefaultCaret caret = (DefaultCaret)messageLogText.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        try {
            fileMan = new FileManager(router, group);
            fileManForm = new FileManagerForm(fileMan);
            fileMan.listFiles();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(self, "Filemanager failed.");
        }
    }

    private void handleButtons() {
        fileButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fileManForm.setVisible(true);
            }
        });
        sendButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String message = messageText.getText();
				if (message.isEmpty()){
					return;
				}
                messageText.setText("");
                group.send(message);
            }
        });
        leaveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                group.leave();
                setVisible(false);
            }
        });
		
		messageText.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String message = messageText.getText();
				if (message.isEmpty()){
					return;
				}
                messageText.setText("");
                group.send(message);
			}
		});
		
		clearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				messageLogText.setText("");
			}
		});

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                fileMan.stop();
                group.leave();
                setVisible(false);
            }
        });
    }

    public void messageReceived(GroupMessage message) {
        Calendar cal = Calendar.getInstance();
		cal.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");
		
		/**
			(d MM yyyy)
			
			
			import java.text.SimpleDateFormat;
			DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
			String date = DATE_FORMAT.format(today);
			System.out.println(date);
			
			(MMM d, ''yy)
		
		**/
		
		
		String line = message.getSender() + ": " +
            message.getMessage();
		messageLogText.append(line+"\n\n");
		messageLogText.append("\t"+"\t"+"\t"+"\t"+"Received "+sdf.format(cal.getTime())+"\n");
    }

    public void memberJoined(MemberAdd member) {
        String name = member.getName();
        if (member.isNewMember()) {
            String line = name + " has joined the group";
            messageLogText.append(line+"\n\n");
        }
        if (! userListModel.contains(name)) {
            userListModel.addElement(member.getAccount());
        }
    }

    public void memberLeft(MemberDel member) {
        System.out.println("%%");
        String line = member.getName() + " has left the group";
        messageLogText.append(line+"\n\n");
        userListModel.removeElement(member.getAccount());
    }



    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        messageLogText = new javax.swing.JTextArea();
        sendButton = new javax.swing.JButton();
        messageText = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        memberList = new javax.swing.JList();
        inviteButton = new javax.swing.JButton();
        leaveButton = new javax.swing.JButton();
        fileButton = new javax.swing.JButton();
        clearButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        //setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMaximumSize(new java.awt.Dimension(700, 535));
        setMinimumSize(new java.awt.Dimension(700, 535));
        setPreferredSize(new java.awt.Dimension(700, 535));
        setResizable(false);
        getContentPane().setLayout(null);

        messageLogText.setEditable(false);
        messageLogText.setColumns(20);
        messageLogText.setRows(5);
        jScrollPane1.setViewportView(messageLogText);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(10, 10, 500, 420);

        sendButton.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        sendButton.setText("S E N D");
        sendButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        getContentPane().add(sendButton);
        sendButton.setBounds(430, 440, 80, 30);

        messageText.setColumns(1);
        messageText.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
        getContentPane().add(messageText);
        messageText.setBounds(10, 440, 410, 40);

        jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Logged-in Users");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(520, 10, 140, 30);

        memberList.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
        memberList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        memberList.setSelectionBackground(new java.awt.Color(153, 102, 255));
        jScrollPane2.setViewportView(memberList);

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(520, 40, 170, 170);

        //inviteButton.setBackground(new java.awt.Color(255, 255, 255));
        //inviteButton.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        //inviteButton.setText("Invite User");
        //inviteButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        //getContentPane().add(inviteButton);
        //inviteButton.setBounds(520, 220, 170, 25);

        leaveButton.setBackground(new java.awt.Color(221, 113, 113));
        leaveButton.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        leaveButton.setText("Leave Group Chat");
        leaveButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        getContentPane().add(leaveButton);
        leaveButton.setBounds(520, 290, 170, 25);

        fileButton.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        fileButton.setText("File Sharing");
        fileButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        getContentPane().add(fileButton);
        fileButton.setBounds(520, 250, 170, 25);

        clearButton.setFont(new java.awt.Font("Segoe UI", 0, 10)); // NOI18N
        clearButton.setText("c l e a r");
        clearButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        getContentPane().add(clearButton);
        clearButton.setBounds(10, 480, 65, 23);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getClassLoader().getResource("resources/images/MainForm3.jpg"))); // NOI18N
        jLabel1.setText("jLabel1");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(0, 0, 700, 520);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ChatForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ChatForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ChatForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ChatForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChatForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected javax.swing.JButton sendButton;
    protected javax.swing.JButton leaveButton;
    protected javax.swing.JButton inviteButton;
    protected javax.swing.JButton fileButton;
    protected javax.swing.JButton clearButton;
    protected javax.swing.JLabel jLabel1;
    protected javax.swing.JLabel jLabel2;
    protected javax.swing.JList memberList;
    protected javax.swing.JScrollPane jScrollPane1;
    protected javax.swing.JScrollPane jScrollPane2;
    protected javax.swing.JTextArea messageLogText;
    protected javax.swing.JTextField messageText;
    // End of variables declaration//GEN-END:variables
}
